import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yyshort/common/utils/alert_dialog_utils.dart';
import 'package:yyshort/common/widgets/toast.dart';
import 'package:yyshort/pages/ali_player/short_video/SharedDataController.dart';

/// 网络类型枚举
enum NetworkType { mobile, wifi, bluetooth, ethernet, vpn, other, none }

/// 网络状态管理服务 - 基于GetX Service实现
class NetworkService extends GetxService {
  final Connectivity _connectivity = Connectivity();
  final Dio _dio = Dio();
  final String _testApiUrl = "https://api.yyshort.com";
  final Duration _testTimeout = const Duration(seconds: 30);

  // 使用Rx变量让GetX可以监听状态变化
  final RxBool _isConnected = false.obs;
  final RxBool _isApiReachable = false.obs;
  final Rx<NetworkType> _networkType = NetworkType.none.obs;
  final RxList<ConnectivityResult> _currentResults = <ConnectivityResult>[].obs;

  StreamSubscription? _subscription;
  bool _hasShownNoNetworkAlert = false;
  bool _isVerifyingApi = false;

  // 公开的状态获取方法 - 提供响应式和非响应式两种方式
  bool get isConnected => _isConnected.value;
  RxBool get isConnected$ => _isConnected;

  bool get isApiReachable => _isApiReachable.value;
  RxBool get isApiReachable$ => _isApiReachable; // 用于外部监听的响应式变量

  NetworkType get networkType => _networkType.value;
  Rx<NetworkType> get networkType$ => _networkType;

  List<ConnectivityResult> get currentResults => _currentResults.toList();
  RxList<ConnectivityResult> get currentResults$ => _currentResults;

  /// 初始化服务
  Future<NetworkService> init() async {
    if (_subscription != null) {
      await _subscription?.cancel();
    }
    await _checkNetworkStatus();
    _startListening();
    return this;
  }

  /// 检查网络状态
  Future<void> _checkNetworkStatus() async {
    try {
      final results = await _connectivity.checkConnectivity();
      _updateNetworkStatus(results);
      if (_isConnected.value) {
        await _verifyApiReachability();
      } else {
        _isApiReachable.value = false;
      }
    } catch (e) {
      if (kDebugMode) {
        print('网络状态检查失败: $e');
      }
    }
  }

  /// 验证接口可达性
  Future<void> _verifyApiReachability() async {
    if (_isVerifyingApi) return;
    _isVerifyingApi = true;

    try {
      final response = await _dio.head(
        _testApiUrl,
        options: Options(
          sendTimeout: _testTimeout,
          receiveTimeout: _testTimeout,
          validateStatus: (status) => status != null,
        ),
      );

      _isApiReachable.value =
          response.statusCode != null && response.statusCode! < 500;

      if (kDebugMode) {
        print(
          '接口验证结果：${_isApiReachable.value ? "可达" : "不可达"}，状态码：${response.statusCode}',
        );
      }

      // 接口恢复可达时触发刷新事件
      if (_isApiReachable.value) {
        eventBus.fire(NetWorkRefreshEvent());
      }
    } on DioException catch (e) {
      _isApiReachable.value = false;
      if (kDebugMode) {
        if (e.type == DioExceptionType.connectionTimeout ||
            e.type == DioExceptionType.receiveTimeout) {
          print('接口验证超时（${_testTimeout.inSeconds}秒）');
        } else if (e.type == DioExceptionType.connectionError) {
          print('接口连接失败：${e.message}');
        } else {
          print('接口验证错误：${e.type} - ${e.message}');
        }
      }
    } catch (e) {
      _isApiReachable.value = false;
      if (kDebugMode) {
        print('接口验证未知错误：$e');
      }
    } finally {
      _isVerifyingApi = false;
    }
  }

  /// 开始监听网络变化
  void _startListening() {
    _subscription = _connectivity.onConnectivityChanged.listen(
      (results) {
        _updateNetworkStatus(results);
        if (_isConnected.value) {
          _verifyApiReachability();
        } else {
          _isApiReachable.value = false;
        }
      },
      onError: (error) {
        if (kDebugMode) {
          print('网络监听错误: $error');
        }
      },
    );
  }

  /// 更新网络状态
  void _updateNetworkStatus(List<ConnectivityResult> results) {
    _currentResults.assignAll(results);
    final bool wasConnected = _isConnected.value;

    _isConnected.value =
        results.isNotEmpty &&
        !results.contains(ConnectivityResult.none) &&
        !results.every((result) => result == ConnectivityResult.none);

    if (_isConnected.value) {
      if (results.contains(ConnectivityResult.wifi)) {
        _networkType.value = NetworkType.wifi;
      } else if (results.contains(ConnectivityResult.mobile)) {
        _networkType.value = NetworkType.mobile;
      } else if (results.contains(ConnectivityResult.ethernet)) {
        _networkType.value = NetworkType.ethernet;
      } else if (results.contains(ConnectivityResult.vpn)) {
        _networkType.value = NetworkType.vpn;
      } else if (results.contains(ConnectivityResult.bluetooth)) {
        _networkType.value = NetworkType.bluetooth;
      } else if (results.contains(ConnectivityResult.other)) {
        _networkType.value = NetworkType.other;
      }
    } else {
      _networkType.value = NetworkType.none;
    }

    if (kDebugMode) {
      print(
        '基础网络状态变化: ${wasConnected ? "连接" : "断开"} -> ${_isConnected.value ? "连接" : "断开"}',
      );
    }
    // 网络从连接变为断开时显示提示
    if (!_isConnected.value && wasConnected) {
      showNoNetworkAlert();
    }

    // 核心修改：基础网络恢复时，仅标记需要刷新，等待接口验证结果
    if (_isConnected.value && !wasConnected) {
      _hasShownNoNetworkAlert = false;

      _checkNetworkStatus();
      if (kDebugMode) {
        print('基础网络恢复，等待接口验证结果后决定是否刷新');
      }
    }
  }

  /// 显示无网络提示
  void showNoNetworkAlert() {
    if (!_hasShownNoNetworkAlert && !kIsWeb) {
      _hasShownNoNetworkAlert = true;

      WidgetsBinding.instance.addPostFrameCallback((_) {
        final context = Get.context;
        if (context != null) {
          final String title = _isApiReachable.value
              ? "网络访问失败".tr
              : "网络连接已断开".tr;
          final String content = _isApiReachable.value
              ? "网络连接异常。请确保您的设备已连接到稳定的网络，或尝试切换网络后重试。".tr
              : "请打开移动数据或连接到 WLAN 以访问数据".tr;

          toastInfo(msg: content);

          // AlertDialogUtils.showPlatformDialog(
          //   context: context,
          //   title: title,
          //   content: content,
          //   confirmText: "检查网络".tr,
          //   cancelText: "取消".tr,
          //   onConfirm: () async {
          //     openNetworkSettings();
          //     _hasShownNoNetworkAlert = false;
          //     if (_isConnected.value) {
          //       _verifyApiReachability();
          //     }
          //   },
          //   onCancel: () {
          //     _hasShownNoNetworkAlert = false;
          //   },
          // );
        } else {
          if (kDebugMode) {
            print('上下文为空，无法显示提示');
          }
        }
      });
    }
  }

  /// 打开网络设置
  Future<void> openNetworkSettings() async {
    Uri url;

    if (Platform.isIOS) {
      url = Uri.parse('app-settings://root=General&path=Network');
    } else if (Platform.isAndroid) {
      url = Uri.parse(
        'intent://settings/#Intent;action=android.settings.WIRELESS_SETTINGS;end',
      );
    } else {
      throw '不支持的平台';
    }

    if (await canLaunchUrl(url)) {
      await launchUrl(url, mode: LaunchMode.externalApplication);
    } else {
      throw '无法打开网络设置页面';
    }
  }

  /// 重新检查接口可达性
  Future<void> recheckApiReachability() async {
    if (_isConnected.value) {
      await _verifyApiReachability();
    }
  }

  /// 判断是否连接WiFi
  bool isWifiConnected() {
    return _isConnected.value && _networkType.value == NetworkType.wifi;
  }

  /// 判断是否连接移动数据
  bool isMobileDataConnected() {
    return _isConnected.value && _networkType.value == NetworkType.mobile;
  }

  /// 释放资源
  @override
  void onClose() {
    _subscription?.cancel();
    _dio.close();
    super.onClose();
  }
}

// 全局导航键
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
